#!/usr/bin/python
# -*- coding: UTF-8 -*-
import hashlib
import io
import os
from datetime import datetime

import helper

# 定义常见的图片扩展名
IMAGE_EXTENSIONS = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff', '.webp')


def is_image_file(file_path):
    if file_path:
        return file_path.lower().endswith(IMAGE_EXTENSIONS)
    return False


def get_file_hash(file_path):
    hasher = hashlib.md5()  # 可以使用 md5, sha256 等
    with open(file_path, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hasher.update(chunk)
    return hasher.hexdigest()


def file_exists(path, file_md5):
    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        if get_file_hash(file_path) == file_md5:
            return True
    return False


class FileSave:
    __file = None

    def __init__(self, file, file_path):
        self.__file = file
        self.file_path = file_path
        self.save_img_path = os.environ.get('save_img_path')
        self.save_file_path = os.environ.get('save_file_path')
        self.relative_path = os.environ.get('relative_path')
        self.custom_date_path = datetime.now().strftime(os.environ.get('custom_date_formate'))
        self.custom_markdown_url = datetime.now().strftime(os.environ.get('custom_markdown_url'))
        self.run()

    def run(self):
        helper.notify('Saving', 'Please wait for a while')
        ori_filename = None
        save_file = None
        if self.file_path:
            save_path = os.path.join(self.save_file_path, self.custom_date_path)
            os.makedirs(save_path, exist_ok=True)
            file_md5 = get_file_hash(self.file_path)
            ori_filename = os.path.basename(self.file_path)
            _, file_extension = os.path.splitext(self.file_path)
            save_file = os.path.join(save_path, file_md5 + file_extension)
            if file_exists(save_path, file_md5):
                helper.notify('Existing', '文件已存在')
            else:
                os.system('cp {} {}'.format(self.file_path, save_file))
        elif self.__file is not None:
            save_path = os.path.join(self.save_img_path, self.custom_date_path)
            os.makedirs(save_path, exist_ok=True)
            # 图片后缀
            file_path, point, suffix = self.__file.filename.rpartition('.')
            # 图片格式
            file_format = self.__file.format
            buffer = io.BytesIO()
            self.__file.save(buffer, file_format)
            image_bytes = buffer.getvalue()
            md5_hasher = hashlib.md5()
            md5_hasher.update(image_bytes)
            file_md5 = md5_hasher.hexdigest()
            ori_filename = file_md5 + '.' + suffix
            if file_exists(save_path, file_md5):
                helper.notify('Existing', '文件已存在')
            else:
                save_file = os.path.join(save_path, ori_filename)
                self.__file.save(save_file)
        markdown_url = self.custom_markdown_url.format(ori_filename=ori_filename, save_file=save_file)
        helper.notify('Success', markdown_url)
        # 打印结果，由 workflow 复制粘贴
        if is_image_file(save_file):
            print(markdown_url.replace(self.relative_path, '..'))
        else:
            print(markdown_url.replace('!', ''))
